package com.androway.activity;

import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Toast;

import com.androway.domains.News;
import com.androway.model.AbstractModel.OnChangedListener;
import com.androway.model.NewsModel;
import com.androway.services.Requester.RequestType;
import com.androway.widget.NewsAdapter;

public class NewsFragment extends Fragment
{
	private FragmentActivity activity;
	private NewsModel model = new NewsModel();
	private NewsAdapter adapter = null;
	public static int identifier = 0;
	public static String name = "News";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance)
	{
		SearchView view;
		ListView newsList;

		activity = (FragmentActivity) super.getActivity();
		view = (SearchView) activity.findViewById(R.id.newsView);
		newsList = (ListView) activity.findViewById(R.id.newsList);
		adapter = new NewsAdapter(activity, model.getNews());
		newsList.setAdapter(adapter);
		this.model.setListener(new OnChangedListener()
		{
			public void onSuccess(RequestType type, String service)
			{
				if (type == RequestType.GET)
					NewsFragment.this.update(NewsFragment.this.model.getNews());
			}

			public void onError(RequestType type, String errorMessage)
			{
				Toast.makeText(NewsFragment.this.activity, errorMessage, Toast.LENGTH_LONG).show();
			}
		});
		view.setOnQueryTextListener(new OnQueryTextListener()
		{

			@Override
			public boolean onQueryTextChange(String newText)
			{
				List<News> newsList;

				newsList = NewsFragment.this.model.search(newText);
				NewsFragment.this.update(newsList);
				return true;
			}

			@Override
			public boolean onQueryTextSubmit(String query)
			{
				List<News> newsList;

				newsList = NewsFragment.this.model.search(query);
				NewsFragment.this.update(newsList);
				return true;
			}
		});

		System.out.println("Inflate");
		return (getActivity().getLayoutInflater().inflate(R.layout.activity_news, container, false));
	}

	protected void update(List<News> news)
	{
		adapter.update(model.getNews());
	}
}
